package com.example.contoller.interceptor;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.pojo.common.IZlyJSONResult;
import com.example.utils.JsonUtils;

public class OneInterceptor implements HandlerInterceptor{
	final static Logger log = LoggerFactory.getLogger(OneInterceptor.class);
	/**
	 * 在请求处理之前进行调用（Controller方法调用之前）
	 * @throws Exception 
	 */
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object object) throws Exception {
		System.out.println(this.getClass()+"\t被拦截器 one 拦截.   放行..... ");
		return true;
	}
	
	/**
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	public void postHandle(HttpServletRequest request,HttpServletResponse response,Object object,ModelAndView mv) {
	}
	
	/**
	 * 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图执行之后执行
	 * （主要是用于进行资源清理工作）
	 */
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object object,Exception ex) {
	}
	
	public void returnErrorResponse(HttpServletResponse response,IZlyJSONResult result) throws IOException{
		OutputStream out =null;
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/json");
			out =response.getOutputStream();
			out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(out!=null){
				out.close();
			}
		}
		
	}
}
